package com.uzhie.jt808;

import com.uzhie.jt808.msg.JT808MsgBean;
import com.uzhie.jt808.spring.MethodInvoke;
import com.uzhie.jt808.util.JT808ProtocolUtil;
import io.netty.buffer.ByteBufUtil;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationTargetException;

/**
 * Created by TangFei on 2018/7/17.
 */
public class JT808Dispatcher {

    private Logger logger = Logger.getLogger(this.getClass());

    private MethodInvoke methodInvoke;

    public void setMethodInvoke(MethodInvoke methodInvoke) {
        this.methodInvoke = methodInvoke;
    }

    public JT808MsgBean dispatch(JT808MsgBean msgBean) throws InvocationTargetException, IllegalAccessException {
        logger.info("来自终端的请求 SIM卡号：" + msgBean.getHeader().getSimNum() + " 消息ID：" + msgBean.getHeader().getHexMsgID() + " 消息体：" + ByteBufUtil.hexDump(msgBean.getBodyBytes()));
        logger.info("通道 " + msgBean.getChannelHandlerContext().channel());
        try {
            Object invoke = methodInvoke.invoke(msgBean.getHeader().getMsgID(), msgBean);
            return (JT808MsgBean) invoke;
        } catch (NullPointerException e) {
            logger.error("没有找到请求的指令：" + msgBean.getHeader().getHexMsgID());
            byte[] bodyBytes = JT808ProtocolUtil.commonRespBodyBytes(msgBean.getHeader().getMsgID(), msgBean.getHeader().getFlowNum(), 1);
            return JT808ProtocolUtil.build808Obj(msgBean.getHeader().getMsgID(), msgBean.getHeader().getFlowNum(), msgBean.getHeader().getSimNum(), bodyBytes);
        }
    }


}
